package com.diyizu.youdianda.filtet;

import com.alibaba.fastjson.JSON;
import com.diyizu.youdianda.common.R;
import com.diyizu.youdianda.entity.YddUser;
import com.diyizu.youdianda.util.JwtUtils;
import com.diyizu.youdianda.util.UserID;
import com.sun.prism.impl.BaseContext;
import io.jsonwebtoken.Claims;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//@WebFilter
public class LoginCheckFilter implements Filter {
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //获取本次请求的URI
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        String uri = request.getRequestURI();

        //判断本次请求, 是否需要登录, 才可以访问
        String[] urls=new String[]{
                "/index/login",
                "/common/**",
                "/user/sendMsg",

                "/home/index/login",
                "/index/index",
                "/index/new",
                "/index/hot",

                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };

        boolean check = check(urls, uri);

        //如果不需要，则直接放行
        if (check){
            filterChain.doFilter(request,response);
            return;
        }

        String token = request.getHeader("token");

        //判断登录状态，如果已登录，则直接放行
        if (JwtUtils.verifyToken(token)) {
            Claims claims = JwtUtils.getClaims(token);
            if (claims!=null){
                long id = (Integer) claims.get("id");
                UserID.setCurrentId(id+"");

                filterChain.doFilter(request,response);
                return;
            }
        }

        //判断移动端登录状态，如果已登录，则直接放行
//        if (request.getSession().getAttribute("user")!=null){
//            Long id = (long)request.getSession().getAttribute("user");
//
//            //BaseContext.setCurrentId(id);
//
//            filterChain.doFilter(request,response);
//            return;
//        }
        //如果未登录, 则返回未登录结果
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    public boolean check(String[] urls,String uri){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, uri);
            if (match){
                return true;
            }
        }
        return false;
    }
}
